#! /usr/bin/env python
#coding=utf-8

import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../"))

from utils import ResterHelper
from utils import ResterStringBuilder

class ProcessResults(ResterStringBuilder):
    def __init__(self, keys, row):
        for idx, key in enumerate(keys):
            self[key] = row[idx]
    def getStr(self, xargs=None, keys=None):
        ordered_keys =  ("prefix", "type", "dacUser", "dacGroup", "dacMode", "selinuxLabel", "value")
        return ResterStringBuilder.getStr(self, xargs, ordered_keys)
class ConfigResults(ResterStringBuilder):
    def __init__(self, keys, row):
        for idx, key in enumerate(keys):
            self[key] = row[idx]

class ParameterRestMgr(object):
    def __init__(self, product):
        self._product = product

    def get_all(self, xargs=None):
        keys = ("prefix", "type", "dacUser", "dacGroup", "value", "dacMode", "selinuxLabel")
        sqlcmd = "select %s from parameters" % ", ".join(keys)
        cursor = self._product.getCursor()
        cursor.execute(sqlcmd)

        processes = []
        for row in cursor:
            processes.append(ProcessResults(keys, row))
        return processes

    def GetDetails(self, id, args):
        if id != '1':
            return
        param = args["param"]
        keys = ("prefix", "type", "dacUser", "dacGroup", "dacMode", "selinuxLabel", "value")
        sqlcmd = "select %s from parameters where prefix=\"%s\"" % (", ".join(keys), param)
        cursor = self._product.getCursor()
        cursor.execute(sqlcmd)

        processes = []
        for row in cursor:
            processes.append(ProcessResults(keys, row))
        if (len(processes) == 0):
            return processes
        self.GetParamGroup(processes, args["param"])
        self.GetParamUser(processes, args["param"])
        self.GetParamMac(processes, args["param"])
        self.GetParamDac(processes, args["param"])
        return processes

    def GetParamMac(self, res, param):
        if res[0]["selinuxLabel"] != "":
            return
        cursor = self._product.getCursor()
        # get Mac mode
        while param.rfind(".") != -1 and res[0]["selinuxLabel"] == "":
            sqlcmd = "select %s from parameters where prefix=\"%s\"" % ("selinuxLabel", param[:param.rfind(".") + 1])
            cursor.execute(sqlcmd)
            for row in cursor:
                res[0]["selinuxLabel"] = row[0]
            param = param[:param.rfind(".")]
        return

    def GetParamDac(self, res, param):
        if res[0]["dacMode"] != 0:
            return
        cursor = self._product.getCursor()
        # get Mac mode
        while param.rfind(".") != -1 and res[0]["dacMode"] == 0:
            sqlcmd = "select %s from parameters where prefix=\"%s\"" % ("dacMode", param[:param.rfind(".") + 1])
            cursor.execute(sqlcmd)
            for row in cursor:
                res[0]["dacMode"] = row[0]
            param = param[:param.rfind(".")]
        return

    def GetParamGroup(self, res, param):
        if res[0]["dacGroup"] != "":
            return
        cursor = self._product.getCursor()
        # get real group
        while param.rfind(".") != -1 and res[0]["dacGroup"] == "":
            sqlcmd = "select %s from parameters where prefix=\"%s\"" % ("dacGroup", param[:param.rfind(".") + 1])
            cursor.execute(sqlcmd)
            for row in cursor:
                res[0]["dacGroup"] = row[0]
            param = param[:param.rfind(".")]
        return

    def GetParamUser(self, res, param):
        if res[0]["dacUser"] != "":
            return
        cursor = self._product.getCursor()
        # get Mac mode
        while param.rfind(".") != -1 and res[0]["dacUser"] == "":
            sqlcmd = "select %s from parameters where prefix=\"%s\"" % ("dacUser", param[:param.rfind(".") + 1])
            cursor.execute(sqlcmd)
            for row in cursor:
                res[0]["dacUser"] = row[0]
            param = param[:param.rfind(".")]
        return

    def doRestRequest(self, id, mod, args):
        mCmdMap = {
            'Getconfig':self.GetServiceConfig,
            'details':self.GetDetails,
            'checkServiceDac':self.GetServiceDac,
        }
        if mod in mCmdMap.keys():
            vals = mCmdMap[mod](id, args)
            if vals != None:
                return ResterHelper.build_array_content(vals, args)
        return ""

    def GetServiceConfig(self, serviceName, args):
        keys = ("uid", "secon", "gid", "name")
        sqlcmd = "select %s from config_service where name=\"%s\"" % (", ".join(keys), args["service"])
        cursor = self._product.getCursor()
        cursor.execute(sqlcmd)
        res = []
        for row in cursor:
            res.append(ConfigResults(keys, row))
        return res
    def GetParamInfo(self, res, param):
        keys = ("dacUser", "dacGroup", "dacMode", "selinuxLabel", "prefix")
        sqlcmd = "select %s from parameters where prefix=\"%s\"" % (", ".join(keys), param)
        cursor = self._product.getCursor()
        cursor.execute(sqlcmd)
        for row in cursor:
            for idx, key in enumerate(keys):
                res[0][key] = row[idx]
        return res
    def GetServiceDac(self, id, args):
        if id != '2':
            return
        keys = ("dacUser", "dacGroup", "dacMode", "selinuxLabel", "serviceName", "userNames", "prefix")
        row = ["", "", 0, "", "", "", ""]
        res = []
        res.append(ConfigResults(keys, row))
        self.GetParamInfo(res, args["param"])
        if res[0]["prefix"] == "":
            return res
        self.GetGroupUsers(res)
        self.GetServiceInfo(args["service"], res)
        self.GetParamGroup(res, args["param"])
        self.GetParamUser(res, args["param"])
        self.GetParamMac(res, args["param"])
        self.GetParamDac(res, args["param"])
        return res
    def GetServiceInfo(self, serviceName, res):
        keys = ("uid", "secon", "gid", "name")
        sqlcmd = "select %s from config_service where name=\"%s\"" % (", ".join(keys), serviceName)
        cursor = self._product.getCursor()
        cursor.execute(sqlcmd)
        for row in cursor:
            res[0]["serviceUid"] = row[0]
            res[0]["serviceSecon"] = row[1]
            res[0]["serviceGid"] = row[2] #service gid
            res[0]["serviceName"] = row[3] #service name
        return res
    def GetParamName(self, res, param):
        sqlcmd = "select prefix from parameters where prefix=\"%s\"" % (param)
        cursor = self._product.getCursor()
        cursor.execute(sqlcmd)

        for row in cursor:
            res[0]["paramPrefix"] = row[0]
        return res
    def GetGroupUsers(self, res):
        if res[0]["dacGroup"] == "":
            res[0]["userNames"] = "root"
            return res
        sqlcmd = "select userNames from group_table where name=\"%s\"" % (res[0]["dacGroup"])
        cursor = self._product.getCursor()
        cursor.execute(sqlcmd)

        for row in cursor:
            res[0]["userNames"] = row[0]
        return res

if __name__ == "__main__":
    import products

    product_mgr = products.Products()
    prod = product_mgr.get_product_by_name("openharmony", "rk3568")
    prod.load_db()

    mgr = ParameterRestMgr(prod)

